<?php
namespace app\index\controller;
use app\index\controller\BaseController;
use app\libs\Predis;
use think\Cache;
use think\Config;
use app\index\middleware\Auth;
use think\Db;

class User extends BaseController
{
    // 注册
    public function register()
    {
        $reqData['phone'] = $this->request->post('phone');
        $reqData['password'] = $this->request->post('password');
        $reqData['captcha'] = $this->request->post('captcha');
        $reqData['chains'] = $this->request->post('chains','','trim');
        $reqData['openid'] = $this->request->post('openid','','trim');
        // 表单验证
        $validata = $this->validate($reqData,'app\index\validate\UserRegister');
        if (true !== $validata) {
            // 验证失败 输出错误信息
            $this->result['status'] = -1;
            $this->result['msg'] = $validata;
            return json_encode($this->result);
        }
        $result = $this->getBusiness('User')->register($reqData);
        return json_encode($result);
    }

    /**
     * login
     * @return false|
     */
    public function login()
    {
        $phone = $this->request->post('phone');
        $password = $this->request->post('password');
        $captcha = $this->request->post('captcha');
        $login_type = (int)$this->request->post('login_type'); // 1.密码登录 2.手机号登录 3.微信登录
        $code = $this->request->post('code');

        // 表单验证
        if ($login_type == 1){
            $reqData = compact('phone','password','login_type');
            $validata = $this->validate($reqData,'app\index\validate\UserLoginPwd');
        }
        if ($login_type == 2){
            $reqData = compact('phone','captcha','login_type');
            $validata = $this->validate($reqData,'app\index\validate\UserLoginCode');
        }
        if (true !== $validata) {
            // 验证失败 输出错误信息
            $this->result['status'] = -1;
            $this->result['msg'] = $validata;
            return json_encode($this->result);
        }
        $result = $this->getBusiness('User')->login($phone,$password,$captcha,$login_type,$code);
        return json_encode($result);
    }
    // 找回密码 第一步
    public function setpassword()
    {
         $reqData['phone'] = $this->request->post('phone');
         $reqData['captcha'] = $this->request->post('captcha');

        // 表单验证
        $validata = $this->validate($reqData,'app\index\validate\UserSetPassword');
        if (true !== $validata) {
            // 验证失败 输出错误信息
            $this->result['status'] = -1;
            $this->result['msg'] = $validata;
            return json_encode($this->result);
        }

        $result = $this->getBusiness('User')->setpassword($reqData['phone'],$reqData['captcha']);
        return json_encode($result);
    }

    // 找回密码 第二步
    public function newpassword()
    {
        $reqData['phone'] = $this->request->post('phone');
        $reqData['password'] = $this->request->post('password');

        // 表单验证
        $validata = $this->validate($reqData,'app\index\validate\UserNewPassword');
        if (true !== $validata) {
            // 验证失败 输出错误信息
            $this->result['status'] = -1;
            $this->result['msg'] = $validata;
            return json_encode($this->result);
        }

        $result = $this->getBusiness('User')->newpassword($reqData['phone'],$reqData['password']);
        return json_encode($result);
    }

    /**
     * 收藏行为
     * @return false|string
     */
    public function collectBehavior(){
        $reqData['identification'] = $this->request->get('identification');
        $reqData['type'] = $this->request->get('type');
        $uuid = $this->request->dispatch()['user_no'];

        // 表单验证
        $validata = $this->validate($reqData,'app\index\validate\UserCollectArticle');
        if (true !== $validata) {
            // 验证失败 输出错误信息
            $this->result['status'] = -1;
            $this->result['msg'] = $validata;
            return json_encode($this->result);
        }

        $result = $this->getBusiness('User')->collectBehavior($reqData['identification'],Config::get('collect.'. $reqData['type']),$uuid);
        return json_encode($result);
    }

    /**
     * 取消收藏
     * @return false|string
     */
    public function cancelCollection()
    {
        $reqData['identification'] = $this->request->get('identification');
        $reqData['type'] = $this->request->get('type');
        $uuid = $this->request->dispatch()['user_no'];

        // 表单验证
        $validata = $this->validate($reqData,'app\index\validate\UserCollectArticle');
        if (true !== $validata) {
            // 验证失败 输出错误信息
            $this->result['status'] = -1;
            $this->result['msg'] = $validata;
            return json_encode($this->result);
        }

        $result = $this->getBusiness('User')->cancelCollection($reqData['identification'],Config::get('collect.'. $reqData['type']),$uuid);
        return json_encode($result);
    }

    /**
     * 上传接口
     * @return \think\response\Json
     */
    public function uploads(){
        // 获取表单上传文件
        $file = request()->file('file');
        //file_put_contents('1.txt',json_encode($_FILES));
        if(empty($file)) {
            //$this->error('请选择上传文件');
            return json(['errcode'=>'10001','msg'=>'请选择上传文件','data'=>[]]);
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH.'public'.DS.'upload');
        //如果不清楚文件上传的具体键名，可以直接打印$info来查看
        //获取文件（文件名），$info->getFilename()  ***********不同之处，笔记笔记哦
        //获取文件（日期/文件名），$info->getSaveName()  **********不同之处，笔记笔记哦
        $filename = $info->getSaveName();  //在测试的时候也可以直接打印文件名称来查看

        if($filename){
            $url = config('localip').'/upload/'.$filename;
            $url = str_replace('\\', '/', $url);
            return json(['errcode'=>'0','msg'=>'上传成功','data'=>['url'=>$url]]);
        }else{
            // 上传失败获取错误信息
            return json(['errcode'=>'10003','msg'=>'token不存在','data'=>[]]);
        }

    }

    /**
     * 查看用户是否有发布新闻和项目的权限
     * @return array
     * @throws
     */
    public function publish()
    {
        $uuid = $this->request->dispatch()['user_no'];
        $userinfo = db('user_auth')
            ->where('status',1)
            ->where('user_no',$uuid)
            ->field('is_pub_news,is_pub_project')
            ->find();

        if (empty($userinfo)){
            $userinfo = [];
        }
        $result = compact('userinfo');
        $this->result['status'] = 1;
        $this->result['data'] = $result;
        return json_encode($this->result);
    }

    /**
     * 用户指挥舱
     */
    public function tinyWindow()
    {
        $dispatch = $this->request->dispatch();
        // 用户未登录显示蒙层
        if (!isset($dispatch['user_no'])){
            $this->result['status'] = -3;
            return json_encode($this->result);
        }
        /****关注的项目****/
        $top=array();
        for ($i=1;$i<=7;$i++){
            //选择表名
            $tbl=Config::get('collect.'.$i);
            $top[$tbl]=db('user_collect_type'.$tbl)->where('status',1)->where('user_no',$dispatch['user_no'])->count();
        }
        $result['collect'] = array_sum($top);
        $project=db('project')
            ->field('follow_status,count(id) as total')
            ->where('status',1)
            ->where('user_no',$dispatch['user_no'])
            ->where('follow_status','in','2,3')
            ->group('follow_status')
            ->select();

        /****在跟和落地****/
        foreach ($project as $value){
            if ($value['follow_status']==2){
                $result['with']=$value['total'];
            }elseif ($value['follow_status']==3){
                $result['deep']=$value['total'];
            }else{
                false;
            }
        }
        if (!isset($result['with'])){
            $result['with']=0;
        }
        if (!isset($result['deep'])){
            $result['deep']=0;
        }
        /****监控****/
        $result['monitor']=db('project')
            ->where('status',1)
            ->where('user_no',$dispatch['user_no'])
            ->where('is_monitor','1')
            ->count();
        /****推送项目****/
        $result['push']=db('push_user_chain')
            ->where(['status'=>1,'is_read'=>0])
            ->where('user_no',$dispatch['user_no'])
            ->count();
        $this->result['status']=1;
        $this->result['msg']='succeess';
        $this->result['data']=$result;
        return json_encode($this->result);
    }

    /**
     * 问题反馈
     */
    public function feedBack()
    {
        $reqData['content']=$this->request->post('content','','trim');
        $reqData['contacts']=$this->request->post('contacts','','trim');
        $reqData['created_at']=$reqData['updated_at']=date('Y-m-d H:i:s');
        /*****修改数据库******/
        Db::startTrans();
        try {
            Db::connect(Config::get('db_yd'))->table('yd_feedback')->insert($reqData);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = '失败';
            return $this->result;
        }
        return json_encode(array('status'=>1,'msg'=>'success','data'=>[]));
    }
}
